<template>
  <div>
    <FormPanel ref="from" :list="formList" @formChange="changeHandle" :isSubmitBtn="false" :collapse="false"
               :labelWidth="110"></FormPanel>

    <FilterTable ref="table" :columns="columns" :dataSource="tableList" height="auto"
                 :onColumnsChange="columns => (this.columns = columns)" :onRowSelectChange="selectChangeHandle">
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" @click="addHandle()" icon="el-icon-plus" :disabled="isSave">新 增
        </multiuse-button>
        <multiuse-button size="small" type="primary" @click="delHandle()" icon="el-icon-remove-outline"
                         :disabled="isSave">删 除
        </multiuse-button>
      </template>
    </FilterTable>

    <BaseDialog :visible.sync="isaddCar" :width="'80%'" :title="'选择车辆'" destroyOnClose
                :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addCar :orderData="orderData" @close="carcloseHandler"/>
    </BaseDialog>

    <div style="height: 47px"></div>
    <div
        :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDrawer(1)" :disabled="isSave">关 闭</el-button>
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 2)" :disabled="isSave">提 交</multiuse-button>
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 3)" :disabled="isSave">保 存</multiuse-button>
    </div>
  </div>
</template>
<script>
import {
  getAmount,
  getDealerAddress,
  getSelfAddress,
  getDetail,
  getFiAccountType,
  getOrderDetailAmount,
  getOrderDetailType,
  saveOrder
} from '@/api/omSaleP/OrderManagement/OrderImport/index.js';
import {dictionary} from '@/utils/dictMixin';
import selectCar from './selectCar';
import addCar from './addCar';
import moment from 'moment';

export default {
  mixins: [dictionary],
  components: {
    selectCar,
    addCar
  },
  props: ['rowData'],
  data() {
    this.saveData = null;
    return {
      formList: this.createdFrom(),
      columns: this.createdTable(),
      tableList: [],
      isaddCar: false,
      orderData: {},
      json: {},
      dealerCode: '',
      isSave: false,
      orderDetailTypeList: [],
      addressList: [],
      selfAddress: [],
      accountTypeList: [],
      totalAmount: [],
      selectList: [],
      isDisabled: true
    };
  },
  created() {
    // 初始化
    this.initOrder();
  },
  mounted() {
    this.table = this.$refs.table.$refs.pageTable;
  },
  watch: {
    tableList: {
      deep: true,
      handler(newval, oldVal) {
        // console.log(newval, oldVal);
      }
    }
  },
  methods: {
    createdFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '订单信息'
        },
        {
          type: 'INPUT',
          label: '订单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearMonth',
          disabled: true,
          placeholder: '请输入',
          dateType: 'month',
          initialValue: moment().format('YYYY-MM')
        },
        {
          type: 'INPUT',
          label: '订单经销商',
          fieldName: 'dealerCode',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('2105'),
          initialValue: 21051002 // 默认增补订单
        },
        {
          type: 'SELECT',
          label: '订单细分类型',
          fieldName: 'orderDetailType',
          placeholder: '请选择',
          itemList: [],
          disabled: true
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('2104'),
          initialValue: 21041001 // 默认新建
        },
        {
          type: 'SELECT',
          label: '订单紧急度',
          fieldName: 'emergencyType',
          placeholder: '请选择',
          itemList: this.createDictList('2101'),
          initialValue: 21011001,
          rules: [{required: true, message: '请选择', trigger: 'change'}]
        },
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'transportType',
          placeholder: '请选择',
          itemList: this.createDictList('2409'),
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          change: value => {
            this.transportTypeOnChange(value);
          }
        },
        {
          type: 'SELECT',
          label: '收车地址',
          fieldName: 'addressId',
          placeholder: '请选择',
          itemList: [],
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          change: value => {
            this.orderAddressOnChange(value);
          }
        },
        {
          type: 'INPUT',
          label: '送达城市',
          fieldName: 'orderCity',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'linkMan',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '联系电话',
          fieldName: 'linkPhone',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'INPUT',
          numberFormat: true,
          initialValue: 0.00,
          label: '资金可用余额',
          fieldName: 'totalFuelAmount',
          placeholder: '请选择',
          disabled: true
        },
        {
          type: 'INPUT',
          numberFormat: true,
          initialValue: 0.00,
          label: '返利池可用余额',
          fieldName: 'singleRebateFuelAmount',
          disabled: true
        },
        {
          type: 'INPUT',
          numberFormat: true,
          initialValue: 0.00,
          label: '本单返利使用金额',
          fieldName: 'singleRebateFuelTotalAmount',
          disabled: true
        },
        {
          type: 'INPUT',
          numberFormat: true,
          initialValue: 0.00,
          label: '实付总金额',
          fieldName: 'realPayTotalAmount',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '创建人',
          fieldName: 'createdName',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '创建时间',
          fieldName: 'createdAt',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'BREAK_SPACE',
          label: '车辆信息'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          width: 200,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '提报数量',
          dataIndex: 'orderNum',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 150,
          editable: true,
          editType: 'number',
          editRequired: true,
          defaultEditable: true,
          editPattern: /^[1-9]\d*$/,
          summation: true,
          rules: [{required: true, message: '请填写正整数', trigger: 'blur'}],
          onInput: (index, data) => {
            this.changeNum(index, data);
          }
        },
        {
          title: '车辆用途',
          dataIndex: 'vehicleUse',
          width: 150,
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2102'),
          editable: true,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: p => {
            return (
                <el-select
                    size='mini'
                    v-model={p.row.vehicleUse}
                    placeholder='请选择'
                    onChange={value => {
                      p.row.vehicleUse = value;
                      // 如果车辆用途为客户订购，则是否返利默认为是
                      p.row.isRebate = value === 21021001 ? 10041001 : 10041002;
                      // 切换时，重新赋值  true
                      this.reComputedAmount(p.row, true, true);
                    }}
                >
                  {this.createDictList('2102').map(item => (
                      <el-option key={item.value} label={item.text} value={item.value}/>
                  ))}
                </el-select>
            );
          }
        },
        {
          title: '资金类型',
          dataIndex: 'fundType',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: p => {
            return (
                <el-select
                    size='mini'
                    v-model={p.row.fundType}
                    required
                    placeholder='请选择'
                    onChange={value => {
                      p.row.fundType = value;
                    }}
                >
                  {this.accountTypeList.map(item => (
                      <el-option key={item.accountId} label={item.accountTypeName} value={item.accountId}/>
                  ))}
                </el-select>
            );
          }
        },
        {
          title: '价格类型',
          dataIndex: 'amountType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2136'),
          render: (p) => {
            return <span>{this.createDictText(p.row.amountType, '2136')}</span>;
          },
        },
        {
          title: '采购价格',
          dataIndex: 'afterDiscountAmount',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: p => {
            return (
                <el-select
                    size='mini'
                    v-model={p.row.afterDiscountAmount}
                    required
                    placeholder='请选择'
                    onChange={value => {
                      p.row.afterDiscountAmount = value;
                      this.reComputedAmountTotal();
                    }}
                >
                  {(p.row.afterDiscountAmountList || []).map(item => (
                      <el-option key={Object.keys(item)[0]} label={this.formatNumber(Object.values(item)[0])}
                                 value={this.formatNumber(Object.values(item)[0])}/>
                  ))}
                </el-select>
            );
          }
        },
        {
          title: '市场指导价',
          dataIndex: 'singleAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          numberFormat: true,
          precision: 2,
          align: "right"
        },
        {
          title: '现金折让',
          dataIndex: 'discountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          numberFormat: true,
          precision: 2,
          align: "right"
        },
        {
          title: '建店返利',
          dataIndex: 'buildRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          numberFormat: true,
          precision: 2,
          align: "right"
        },
        {
          title: '是否使用返利',
          dataIndex: 'isRebate',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          editable: false,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: p => {
            return (
                <el-select
                    size='mini'
                    v-model={p.row.isRebate}
                    placeholder='请选择'
                    disabled={p.row.isRebateDisabled}
                    onChange={value => {
                      p.row.isRebate = value;
                      this.reComputedAmount(p.row, true, true);
                    }}
                >
                  {this.createDictList('1004').map(item => (
                      <el-option key={item.value} label={item.text} value={item.value}/>
                  ))}
                </el-select>
            );
          }
        },
        {
          title: '返利冲抵',
          dataIndex: 'singleRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          numberFormat: true,
          precision: 2,
          align: "right"
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配置',
          dataIndex: 'packageName',
          width: 300,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          width: 200,
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    changeHandle(val) {
      this.saveData = val;
    },
    /**
     * 初始化
     */
    async initOrder() {
      this.isSave = true;
      // 判断新增or编辑
      if (this.rowData) {
        this.dealerCode = this.rowData.dealerCode;

        // 订单细分类型
        await this.getOrderDetailType();
        // 收车地址
        await this.getDealerAddress(this.dealerCode);
        // 自提地址
        await this.getSelfAddress();
        // 资金类型
        await this.getFiAccountType(this.dealerCode);
        // 经销商资金
        await this.getTotalAmount(this.dealerCode);

        // 编辑
        // 通过订单id查询订单和订单明细数据
        let res = await getDetail({orderId: this.rowData.orderId});
        if (res.resultCode === 200) {
          let addressId = null;
          for (let i in res.data) {
            this.formList.map(x => {
              if (i === x.fieldName) {
                x.initialValue = res.data[i];
              }
              // 订单细分类型
              if (x.fieldName === 'orderDetailType') {
                x.itemList = this.orderDetailTypeList.map(x => ({text: x.subName, value: x.subId}));
              }
              // 运输方式
              if (x.fieldName === 'transportType') {
                this.transportTypeOnChange(x.initialValue);
              }
              // 收车地址
              if (i === 'addressId') {
                addressId = res.data[i];
              }
              // 经销商资金
              if (x.fieldName === 'totalFuelAmount') {
                x.initialValue = this.formatNumber(this.totalAmount.totalFuelAmount);
              }
              if (x.fieldName === 'singleRebateFuelAmount') {
                x.initialValue = this.formatNumber(this.totalAmount.singleRebateFuelAmount);
              }
            });
          }

          // 赋值收车地址信息
          if (addressId !== null) {
            await this.orderAddressOnChange(addressId);
          }
          // 明细
          this.tableList = res.data.detailDTOList || [];
          for (const car of this.tableList) {
            await this.reComputedAmount(car);
          }
        }
      }
      this.isSave = false;
    },
    /**
     * 获取订单细分类型
     */
    async getOrderDetailType() {
      let res = await getOrderDetailType({isAvailable: 10041001});
      if (res.resultCode === 200) {
        this.orderDetailTypeList = res.data;
      }
    },
    /**
     * 获取收车地址
     */
    async getDealerAddress(dealerCode) {
      let res = await getDealerAddress({dealerCode: dealerCode});
      if (res.resultCode === 200) {
        this.addressList = res.data;
      }
    },
    /**
     * 自提地址
     */
    async getSelfAddress() {
      let res = await getSelfAddress();
      if (res.resultCode === 200) {
        this.selfAddress = res.data;
      }
    },
    /**
     * 选择运输方式
     */
    async transportTypeOnChange(value) {
      this.formList.find(item => item.fieldName === 'addressId').initialValue = '';
      this.formList.find(item => item.fieldName === 'orderCity').initialValue = '';
      this.formList.find(item => item.fieldName === 'linkMan').initialValue = '';
      this.formList.find(item => item.fieldName === 'linkPhone').initialValue = '';
      if (24091002 === value) {
        // 自提
        this.formList.find(item => item.fieldName === 'addressId').itemList = [];
        for (let i in this.selfAddress) {
          if (this.selfAddress[i] !== null && this.selfAddress[i].addressId !== null &&
              typeof (this.selfAddress[i].addressId) !== "undefined") {
            // 添加到收车地址下拉
            this.formList.find(item => item.fieldName === 'addressId').itemList.push({
              text: this.selfAddress[i].address,
              value: this.selfAddress[i].addressId
            });
          }
        }
        // 默认第一条收车地址
        if (this.selfAddress[0] !== null && typeof (this.selfAddress[0]) !== "undefined") {
          this.formList.find(item => item.fieldName === 'addressId').initialValue = this.selfAddress[0].addressId;
          this.formList.find(item => item.fieldName === 'orderCity').initialValue = this.selfAddress[0].cityName;
          this.formList.find(item => item.fieldName === 'linkMan').initialValue = this.selfAddress[0].linkMan;
          this.formList.find(item => item.fieldName === 'linkPhone').initialValue = this.selfAddress[0].linkPhone;
        }
      } else if (24091001 === value) {
        // 经销商收车地址
        this.formList.find(item => item.fieldName === 'addressId').itemList = [];
        (this.addressList || []).map(x => {
          this.formList.find(item => item.fieldName === 'addressId').itemList.push({
            text: x.address,
            value: x.addressId
          });
        });
        // 获取主店收车地址
        let indexAddress = 0;
        for (let i in this.addressList) {
          if (this.addressList[i].addressProperty === 60351001) {
            indexAddress = i;
            break;
          }
        }
        // 未获取到主店收车地址则默认第一条
        if (this.addressList[indexAddress] !== null && typeof (this.addressList[indexAddress]) !== "undefined") {
          this.formList.find(item => item.fieldName === 'addressId').initialValue = this.addressList[indexAddress].addressId;
          this.formList.find(item => item.fieldName === 'orderCity').initialValue = this.addressList[indexAddress].cityName;
          this.formList.find(item => item.fieldName === 'linkMan').initialValue = this.addressList[indexAddress].linkMan;
          this.formList.find(item => item.fieldName === 'linkPhone').initialValue = this.addressList[indexAddress].linkPhone;
        }
      }
    },
    /**
     * 根据运输方式获取收车地址
     * @returns {[]}
     */
    getAddressByTransportType() {
      let addressListTemp = [];
      const transportType = this.formList.find(item => item.fieldName === 'transportType').initialValue;
      if (transportType === 24091002) {
        // 自提
        addressListTemp = this.selfAddress;
      } else if (transportType === 24091001) {
        addressListTemp = this.addressList;
      }
      return addressListTemp;
    },
    /**
     * 选择收车地址事件
     */
    async orderAddressOnChange(value) {
      this.formList.find(item => item.fieldName === 'addressId').initialValue = '';
      this.formList.find(item => item.fieldName === 'orderCity').initialValue = '';
      this.formList.find(item => item.fieldName === 'linkMan').initialValue = '';
      this.formList.find(item => item.fieldName === 'linkPhone').initialValue = '';

      this.getAddressByTransportType().map(address => {
        if (address.addressId === value) {
          this.formList.find(item => item.fieldName === 'addressId').initialValue = address.addressId;
          this.formList.find(item => item.fieldName === 'orderCity').initialValue = address.cityName;
          this.formList.find(item => item.fieldName === 'linkMan').initialValue = address.linkMan;
          this.formList.find(item => item.fieldName === 'linkPhone').initialValue = address.linkPhone;
        }
      });
    },
    /**
     * 查询经销商资金可用余额和返利池可用余额
     */
    async getTotalAmount(dealerCode) {
      let res = await getAmount({dealerCode: dealerCode});
      if (res.resultCode === 200) {
        this.totalAmount = res.data;
      }
    },
    /**
     * 查询资金类型
     */
    async getFiAccountType(dealerCode) {
      let res = await getFiAccountType({dealerCode: dealerCode});
      if (res.resultCode === 200) {
        this.accountTypeList = res.data;
      }
    },
    /**
     * 获取三方资金类型
     */
    getThreePartyAccountType() {
      let accountId = null;
      let index = 0;
      for (let i in this.accountTypeList) {
        // 60051001 : 三方资金类型
        if (this.accountTypeList[i].accountType === 60051001) {
          index = i;
          break;
        }
      }
      if (this.accountTypeList[index]) {
        accountId = this.accountTypeList[index].accountId;
      }
      return accountId;
    },
    /**
     * 选择车辆
     */
    addHandle() {
      // 主单数据
      this.orderData = {
        "dealerCode": this.dealerCode // 经销商代码
      };
      this.isaddCar = true;
      this.saveData = null;
    },
    /**
     * 选择车辆
     * @param carList 选择的车辆
     * @param orderData 订单数据
     * @returns {Promise<void>}
     */
    async carcloseHandler(carList, orderData) {
      this.isaddCar = false;
      this.saveData = null;
      if (carList) {
        carList.forEach(car => {
          // 配置（用于保存）
          car.packageId = car.configId;
          car.packageCode = car.configCode;
          car.packageName = car.configName;
          // 内饰（用于保存）
          car.trimId = car.trimColorId
          car.trimCode = car.trimColor
          car.trimName = car.trimColorName

          // 提报数量
          car.orderNum = 1;
          // 车辆用途：默认客户订购
          car.vehicleUse = 21021001;
          // 资金类型：默认三方融资账户
          car.fundType = this.getThreePartyAccountType();
          // 市场指导价
          car.singleAmount = car.oemDirectivePrice;
          // 是否使用返利：默认是
          car.isRebate = 10041001;
          this.table.EXECUTE_INSERT([car]);
        });
        // 计算价格
        for (const car of this.tableList) {
          await this.reComputedAmount(car, true, true);
        }
      }
    },
    /**
     *
     * 计算价格
     * 编辑初始化:
     *  清空采购价:否
     *  默认第一个:否
     *
     * 选择车辆:
     *  清空采购价:是
     *  默认第一个:是
     *
     * 车辆用途:
     *  清空采购价:是
     *  默认第一个:是
     *
     * 是否使用返利
     *  清空采购价:是
     *  默认第一个:是
     *
     * @param car 当前车辆数据
     * @param isClear 是否清空采购价
     * @param isDefaultPrice 是否设置默认采购价
     * @returns {Promise<void>}
     */
    async reComputedAmount(car, isClear = false, isDefaultPrice = false) {
      // 清空采购价格
      if (isClear) {
        car.afterDiscountAmount = '';
      }
      car.afterDiscountAmountList = [];

      const carData = {
        dealerCode: this.dealerCode,
        productCode: car.productCode,
        vehicleUse: car.vehicleUse,
        singleAmount: car.singleAmount,
        isRebate: car.isRebate,
        singleRebateFuelAmount: this.totalAmount.singleRebateFuelAmount
      };
      let orderAmountData = await getOrderDetailAmount(carData);
      if (orderAmountData.resultCode === 200) {
        car.afterDiscountAmountList = orderAmountData.data.afterDiscountAmountList;

        // 采购价格默认显示第一个价格
        if (car.afterDiscountAmountList && car.afterDiscountAmountList.length > 0 && isDefaultPrice) {
          car.afterDiscountAmount = this.formatNumber(Object.values(car.afterDiscountAmountList[0])[0]);
        }
        car.afterDiscountAmount = this.formatNumber(car.afterDiscountAmount);
        car.discountAmount = this.formatNumber(orderAmountData.data.discountAmount);
        car.discountRuleId = orderAmountData.data.discountRuleId;
        car.singleRuleId = orderAmountData.data.discountRuleId;
        car.buildRebateAmount = this.formatNumber(orderAmountData.data.buildRebateAmount);
        car.buildRuleId = orderAmountData.data.buildRuleId;
        car.singleRebateAmount = this.formatNumber(orderAmountData.data.singleRebateAmount);
        car.singleRebateAmountOrg = this.formatNumber(orderAmountData.data.singleRebateAmountOrg);
        car.discount = orderAmountData.data.discount;
        car.amountType = orderAmountData.data.amountType;
      }

      // 价格类型为常规价格，且返利冲抵大于0时，则是否使用返利可以编辑
      if (car.amountType === 21361005 && (car.singleRebateAmountOrg !== '' && car.singleRebateAmountOrg > 0)) {
        // 取消禁用
        if (car.isRebateDisabled) {
          car.isRebate = 10041001;
          car.isRebateDisabled = false;
        }
      } else {
        // 是否返利为改否，并禁用
        car.isRebate = 10041002;
        car.isRebateDisabled = true;
      }
      this.$forceUpdate();
      this.reComputedAmountTotal();
    },
    reComputedAmountTotal() {
      // 本单返利使用金额
      let singleRebateFuelTotalAmount = 0.0;
      // 实付总金额
      let realPayTotalAmount = 0.0;

      this.tableList.forEach(async car => {
        singleRebateFuelTotalAmount += car.singleRebateAmount * car.orderNum;
        realPayTotalAmount += car.afterDiscountAmount * car.orderNum;
      });

      this.formList.map(x => {
        if (x.fieldName === 'singleRebateFuelTotalAmount') {
          x.initialValue = this.formatNumber(singleRebateFuelTotalAmount);
        }
        if (x.fieldName === 'realPayTotalAmount') {
          x.initialValue = this.formatNumber(realPayTotalAmount);
        }
      });
    },
    changeNum(index, data) {
      let num = '';
      let str = '';
      for (let i in index) {
        num = index[i];
        str = i.split('|')[0];
      }
      let Rep = /^[1-9]\d*$/;
      if (num > 10000000000) {
        this.$notify({
          title: '警告',
          message: '输入数量过大',
          type: 'warning'
        });
        return;
      }
      if (Rep.test(num)) {
        this.reComputedAmountTotal();
      }
    },
    /**
     * 删除选中车辆
     */
    async delHandle() {
      if (this.selectList.length === 0) {
        // 提示
        this.$notify({
          title: '警告',
          message: '请选择数据',
          type: 'warning'
        });
        return;
      }
      await this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.selectList.forEach(data => {
          this.table.EXECUTE_DELETE([data]);
          this.tableList = this.tableList.filter(item => item !== data);
        });
        this.reComputedAmountTotal();
      }).catch(() => {
      });
    },
    selectChangeHandle(rows) {
      this.selectList = rows;
    },
    async closeDrawer(type) {
      if (type === 1) {
        this.$emit('close');
      } else if (type === 2 || type === 3) {
        this.isSave = true;
        if (this.tableList.length < 1) {
          this.$notify({
            title: '警告',
            message: '请选择车辆',
            type: 'warning'
          });
          this.isSave = false;
          return;
        }

        this.$refs.from.SUBMIT_FORM();
        const requireMessage = this.$refs.table.GET_REQUIRED_ERROR();
        if (requireMessage && requireMessage.message) {
          this.isSave = false;
          return this.$message.warning(requireMessage.message);
        }
        if (this.saveData) {
          let order = JSON.parse(JSON.stringify(this.saveData));
          if (this.rowData) {
            order = Object.assign({}, this.rowData, this.saveData);
          }
          if (order.realPayTotalAmount > 1000000000) {
            this.$notify({
              title: '警告',
              message: '实付总金额或返利金额数额过大，请重新进行保存',
              type: 'warning'
            });
            this.isSave = false;
            return;
          }
          let orderDetail = this.tableList;
          let is = false;
          orderDetail.map(x => {
            if (Number(x.orderNum) > 10000000000 || Number(x.orderNum) < 1) {
              is = true;
            }
          });
          if (is) {
            this.$notify({
              title: '警告',
              message: '输入数量过大或过小',
              type: 'warning'
            });
            this.isSave = false;
            return;
          }
          order.detailDTOList = orderDetail;
          order.saveType = 'OEM';
          // 21041001:新建，21041002:已提报待审核
          order.orderStatus = type === 3 ? 21041001 : 21041002;
          order.orderMonth = order.orderYearMonth.split('-')[1];
          order.orderYear = order.orderYearMonth.split('-')[0];
          this.getAddressByTransportType().map(addr => {
            if (order.addressId === addr.addressId) {
              order.orderAddress = addr.address
            }
          });

          let res = await saveOrder(order);
          if (res.resultCode === 200) {
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success'
            });
            this.$emit('close', order);
          } else {
            this.saveData = null;
          }
        }
        this.isSave = false;
      }
    },
    changeValueNum(a) {
      if (!a || isNaN(a)) {
        return 0;
      } else {
        return a;
      }
    },
    formatNumber(val) {
      return Number(val).toFixed(2);
    }
  }
};
</script>
<style lang="less">
.discount {
  text-decoration: underline;
  color: #d1291a;
  cursor: pointer;
}
</style>
